package http_print

import (
	"context"
	"fmt"
	"github.com/imroc/req/v3"
	"print-link/fw_log"
)

type ErrorMessage struct {
	// 代码
	Code int `json:"code" example:"200"`
	// 消息
	Msg string `json:"msg"`
	// 数据集
	Data interface{} `json:"data"`
	//时间戳
	TimeStamp int64 `json:"timestamp"`
}

// Error implements go error interface.
func (msg *ErrorMessage) Error() string {
	return fmt.Sprintf("API Error: %s", msg.Msg)
}

type PrintClient struct {
	*req.Client
}

func NewHttpClient() *PrintClient {
	return &PrintClient{
		Client: req.C().
			SetBaseURL("qeqeqweqwe").
			SetCommonErrorResult(&ErrorMessage{}).
			EnableDumpEachRequest().
			OnAfterResponse(func(client *req.Client, resp *req.Response) error {
				if resp.Err != nil { // There is an underlying error, e.g. network error or unmarshal error.
					return nil
				}
				if errMsg, ok := resp.ErrorResult().(*ErrorMessage); ok {
					resp.Err = errMsg // Convert api error into go error
					return nil
				}
				if !resp.IsSuccessState() {
					//Neither a success response nor a error response, record details to help troubleshooting
					resp.Err = fmt.Errorf("bad status: %s\nraw content:\n%s", resp.Status, resp.Dump())
				}
				return nil
			}),
	}
}

// 获取用户信息
func (c *PrintClient) SendToPrint(ctx context.Context, content string) (okRet map[string]interface{}, errRet map[string]interface{}, err error) {
	// 发送请求
	resp, err := c.R().
		SetContext(ctx).
		SetBody(content).
		SetContentType("application/json;charset=utf-8").
		SetSuccessResult(&okRet).
		SetErrorResult(&errRet).
		Post("http://127.0.0.1:54321")
	fw_log.Slogger.Info(resp)
	return okRet, errRet, err
}
